import md5 from "md5";
import svgCaptcha from 'svg-captcha';
import jwt from 'jsonwebtoken';
import { loginDao, updateAdminDao } from '../dao/userDao';
import { ValidationError } from '../utils/errors';

// export interface TokenPayload {
//   id: number
//   userId: string
//   username: string
//   iat?: number
//   exp?: number
// }

/**
 * 用户登录
 * @param loginInfo 
 * @returns 
 */
export const loginService = async function(loginInfo) {
  loginInfo.password = md5(loginInfo.password)

  // 数据库验证
  let result = await loginDao(loginInfo)
  console.log(result, 'result');
  
  if (result && result.length) {
    const { id, user_id, username, avatar } = result[0]
    // 添加token
    const data = {
      id,
      userId: user_id,
      username,
      avatar
    }
    // token有效期
    let loginPeriod = 1
    if (loginInfo.remember) loginPeriod = loginInfo.remember
    // 生成token
    const token = jwt.sign(data, process.env.JWT_SECRET, {expiresIn: 60 * 60 * 24 * loginPeriod})
    return {
      token,
      data
    }
  } else {
    throw new ValidationError('用户名或密码错误')
  }
  
}

// interface AccountInfo {
//   oldUsername: string;
//   oldPassword: string;
//   userId?: string;
//   username?: string;
//   password?: string;
// }
/**
 * 用户更新
 * @param accountInfo 
 * @returns 
 */
export const updateAdminService = async function(accountInfo) {
  accountInfo.password = md5(accountInfo.password) // 密码加密
  accountInfo.oldPassword = md5(accountInfo.oldPassword) // 密码加密

  const {oldUsername, oldPassword, userId, username, password} = accountInfo
  // 验证旧密码是否正确
  const users = await loginDao({
    username: oldUsername,
    password: oldPassword
  })

  if (users && users.length) {
    const result = await updateAdminDao({
      id: users[0].id,
      userId: userId,
      username: username,
      password: password
    })
    return {
      id: users[0].id,
      userId: userId,
      username: username,
      affectedRows: result.affectedRows
    }
  } else {
    // 用户或密码不正确
    // 抛出自定义错误（异步的），需要结合express-async-errors库
    throw new ValidationError('用户名或密码错误')
  }

}

// 生成登录验证码
export const getCaptchaService = async function() {
  return svgCaptcha.create({
    size: 4,
    ignoreChars: 'iIl10oO',
    noise: 6,
    color: true
  })
}

